package com.me.seckill.service.impl;

import com.me.seckill.constant.RedisKeysConstant;
import com.me.seckill.mapper.StockMapper;
import com.me.seckill.pojo.Stock;
import com.me.seckill.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Function:
 *
 * @author crossoverJie
 *         Date: 30/04/2018 22:39
 * @since JDK 1.8
 */
@Service("DBStockService")
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public int delStock(Stock stock) {
        return stockMapper.delStock(stock);
    }

    @Override
    public int initStock(Stock stock) {
        return stockMapper.addStock(stock);
    }

    @Override
    public int setRedisStock(int goodsId) {
        Stock stock = stockMapper.selectById(goodsId);
        Integer count = stock.getCount();
        redisTemplate.opsForValue().set(RedisKeysConstant.STOCK_COUNT + goodsId, count.toString());
        redisTemplate.opsForValue().set(RedisKeysConstant.STOCK_SALE + goodsId, stock.getSale().toString());
        redisTemplate.opsForValue().set(RedisKeysConstant.STOCK_VERSION + goodsId, stock.getVersion().toString());

        return count;
    }

    @Override
    public Stock getStockById(int id) {
        return stockMapper.selectById(id) ;
    }

    @Override
    public int updateStockById(Stock stock) {
        return stockMapper.updateByPrimaryKeySelective(stock) ;
    }

    @Override
    public int updateStockByOptimistic(Stock stock) {
        return stockMapper.updateByOptimistic(stock);
    }
}
